package com.topscore.uke.ui.activities;

import android.content.res.AssetManager;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.google.gson.Gson;
import com.topscore.uke.R;
import com.topscore.uke.entities.VisitorChartBean;
import com.topscore.uke.entities.VisitorSourceEntity;
import com.topscore.uke.mvp.contractors.GetMyVisitorsContractor;
import com.topscore.uke.mvp.presenters.GetVisitorsPresenter;
import com.topscore.uke.ui.ToolBarCompatActivity;

import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.AxisValue;
import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.view.LineChartView;

public class VisitorsActivity extends ToolBarCompatActivity implements GetMyVisitorsContractor.View {

    @Bind(R.id.root_recycler)
    RecyclerView rootRecycler;

    private RootAdapter mAdapter;
    private BaseQuickAdapter<VisitorSourceEntity,BaseViewHolder> mSourceAdapter;
    private List<ItemEntity> mItemList;
    final int _Type_Chart_Header = 1003, _Type_Source = 1004;

    private LineChartView mLineChartView;

    private GetMyVisitorsContractor.Presenter mPresenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_visitors);
        ButterKnife.bind(this);
        setCentralTitle("访客记录");
        mPresenter = new GetVisitorsPresenter(this);
        initViews();
    }

    private void initViews() {
        initAdapter();
        rootRecycler.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        rootRecycler.setAdapter(mAdapter);
        initData();
    }

    private void initData() {
        mPresenter.getVisitorsData("u005");
//        new Handler(new Handler.Callback() {
//            @Override
//            public boolean handleMessage(Message msg) {
//                if (msg.what == 0) {
//                    mLineChartView.setLineChartData(getLineData());
//                }
//                return false;
//            }
//        }).sendEmptyMessageDelayed(0, 1000);
    }

    private void initAdapter() {
        mSourceAdapter = new BaseQuickAdapter<VisitorSourceEntity, BaseViewHolder>(R.layout.visitor_source_item,new ArrayList<>()) {
            @Override
            protected void convert(BaseViewHolder holder, VisitorSourceEntity item) {
                holder.setText(R.id.source_tv,item.getSource())
                        .setText(R.id.count_tv,item.getCount());
            }
        };
        mItemList = new ArrayList<>();
        mItemList.add(new ItemEntity(_Type_Chart_Header));
        mItemList.add(new ItemEntity(_Type_Source));
        mAdapter = new RootAdapter(mItemList);
    }

//    public LineChartData getLineData() {
//        AssetManager assetManager = getAssets();
//        List<AxisValue> axisValues;
//        try {
//            InputStream inputStream = assetManager.open("visitor_chats.json");
//            byte[] buffer = new byte[inputStream.available()];
//            inputStream.read(buffer);
//            String json = new String(buffer, "utf-8");
//            inputStream.close();
//
//            ChartData response = new Gson().fromJson(json, ChartData.class);
//            List<VisitorChartBean> beanList = response.getData();
//
//            List<Line> lines = new ArrayList<>();
//            List<PointValue> pointValues = new ArrayList<>();
//            axisValues = new ArrayList<>();
//            for (int i = 0; i < beanList.size(); i++) {
//                PointValue value = new PointValue(i, beanList.get(i).getCount());
//                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
//                Date date = dateFormat.parse(beanList.get(i).getTimeDimension());
//                axisValues.add(new AxisValue(i).setLabel(new SimpleDateFormat("MM-dd").format(date)));
//                pointValues.add(value);
//            }
//            Line line = new Line(pointValues);
//            line.setStrokeWidth(1);
//            line.setColor(Color.parseColor("#f8b551"));
//            line.setPointRadius(3);
//            line.setPointColor(Color.parseColor("#f8b551"));
//
//            lines.add(line);
//
//            LineChartData data = new LineChartData(lines);
//
//            Axis axisX = new Axis(axisValues);
//            axisX.setMaxLabelChars(5);
//            Axis axisY = new Axis();
//            axisY.setHasLines(true);
//            axisY.setName("人数(人)");
//            data.setAxisXBottom(axisX);
//            data.setAxisYLeft(axisY);
//            return data;
//        } catch (IOException e) {
//            e.printStackTrace();
//            return null;
//        } catch (ParseException e) {
//            e.printStackTrace();
//            return null;
//        }
//    }

    @Override
    public void onLoading(String loadingMessage) {
        showLoadingDialog(loadingMessage);
    }

    @Override
    public void onLoadFinished() {
        dismissLoadingDialog();
    }

    @Override
    public void onFail(int code, String errorMessage) {
        Toast.makeText(mContext,errorMessage,Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onGetChartDataSuccess(List<VisitorChartBean> entities) {
        List<AxisValue> axisValueList = new ArrayList<>();
        List<PointValue> pointValues = new ArrayList<>();
        for (int i = 0; i < entities.size(); i++) {
            PointValue pointValue = new PointValue(i+1,entities.get(i).getCount());
            AxisValue axisValue = new AxisValue(i+1).setLabel(entities.get(i).getTimeDimension());
            pointValues.add(pointValue);
            axisValueList.add(axisValue);
        }
        Line line = new Line(pointValues);
        line.setStrokeWidth(1);
        line.setColor(Color.parseColor("#f8b551"));
        line.setPointRadius(3);
        line.setPointColor(Color.parseColor("#f8b551"));
        List<Line> lines = new ArrayList<>();
        lines.add(line);
        LineChartData data = new LineChartData(lines);

        Axis axisX = new Axis(axisValueList);
        axisX.setMaxLabelChars(5);
        Axis axisY = new Axis();
        axisY.setHasLines(true);
        axisY.setName("人数(人)");
        data.setAxisXBottom(axisX);
        data.setAxisYLeft(axisY);
        mLineChartView.setLineChartData(data);
    }

    @Override
    public void onGetSourceDataSuccess(List<VisitorSourceEntity> entities) {
        mSourceAdapter.setNewData(entities);
    }

    private class ItemEntity implements MultiItemEntity {

        private int itemType;

        public ItemEntity() {
        }

        private ItemEntity(int itemType) {
            this.itemType = itemType;
        }

        public void setItemType(int itemType) {
            this.itemType = itemType;
        }

        @Override
        public int getItemType() {
            return itemType;
        }
    }

    private class RootAdapter extends BaseMultiItemQuickAdapter<ItemEntity, BaseViewHolder> {

        /**
         * Same as QuickAdapter#QuickAdapter(Context,int) but with
         * some initialization data.
         *
         * @param data A new list is created out of this one to avoid mutable list
         */


        public RootAdapter(List<ItemEntity> data) {
            super(data);
            addItemType(_Type_Chart_Header, R.layout.visitor_chart_header);
            addItemType(_Type_Source, R.layout.visitors_source_layout);
        }

        @Override
        protected void convert(BaseViewHolder viewHolder, ItemEntity item) {
            switch (item.getItemType()) {
                case _Type_Chart_Header:
                    mLineChartView = viewHolder.getView(R.id.visitor_line_chart);
                    break;
                case _Type_Source:
                    RecyclerView recyclerView = viewHolder.getView(R.id.recycler_view);
                    recyclerView.setLayoutManager(new LinearLayoutManager(mContext,LinearLayoutManager.VERTICAL,false));
                    recyclerView.setAdapter(mSourceAdapter);
                    break;
            }
        }
    }

}
